﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SqlSugar;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Dilon.Core.Service
{
    /// <summary>
    /// 操作日志服务
    /// </summary>
    [ApiDescriptionSettings(Name = "OpLog", Order = 100)]
   
    public class SysOpLogService : ISysOpLogService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<SysLogOp> _sysOpLogRep;  // 操作日志表仓储 

        public SysOpLogService(ISqlSugarRepository<SysLogOp> sysOpLogRep)
        {
            _sysOpLogRep = sysOpLogRep;
        }

        /// <summary>
        /// 分页查询操作日志
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("sysOpLog/page")]
        public async Task<dynamic> QueryOpLogPageList([FromQuery] OpLogInput input)
        {
            var opLogs = await _sysOpLogRep.Context.Queryable<SysLogOp>()
                .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Success), u => u.Success == input.Success.Trim())
                .WhereIF(!string.IsNullOrWhiteSpace(input.SearchBeginTime), u => u.OpTime >= DateTime.Parse(input.SearchBeginTime.Trim()) && u.OpTime <= DateTime.Parse(input.SearchEndTime.Trim()))
                .OrderBy(u => u.Id, OrderByType.Desc)
                .Select<OpLogOutput>()
                .ToPagedListAsync(input.PageNo, input.PageSize);

            return XnPageResult<OpLogOutput>.SqlSugarPageResult(opLogs);
        }

        /// <summary>
        /// 清空操作日志
        /// </summary>
        /// <returns></returns>
        [HttpPost("sysOpLog/delete")]
        public async Task ClearOpLog()
        {
            var opLogs = await _sysOpLogRep.Entities.ToListAsync();
            await _sysOpLogRep.DeleteAsync(opLogs);
        }
    }
}
